#include<bits/stdc++.h>
using namespace std;

struct node {
	int val = 0, cnt = 0;
} a[30005];

int Find(int x) {
	while (a[x].val > 0)
		x = a[x].val;
	return x;
}

void add(int x, int cnt_y) {
	while (a[x].val > 0) {
		x = a[x].val;
		a[x].cnt += cnt_y + 1;
	}
}

signed main() {
	int P, x, y;
	char ch;
	cin >> P;
	while (P--) {
		cin >> ch;
		if (ch == 'M') {
			cin >> x >> y;
			if (x != y) {
				a[y].val = x;

				int cnt_y = a[Find(x)].cnt;
//				a[x].cnt += cnt_y + 1;
				add(x, cnt_y);

//				cout << a[x].cnt << " " << a[Find(y)].cnt << endl;
			}
		}
		if (ch == 'C') {
			cin >> x;
			cout << a[x].cnt << endl;
		}
	}
	return 0;
}
